<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 顶部导航栏 - 复用Home.vue的导航栏 -->
    <header class="sticky top-0 z-50 bg-white shadow-md transition-all duration-300">
      <div class="container mx-auto px-4">
        <div class="flex items-center justify-between h-16 md:h-20">
          <!-- Logo -->
          <div class="flex items-center">
            <router-link to="/home" class="flex items-center">
              <i class="fas fa-book text-primary text-2xl md:text-3xl mr-2"></i>
              <span class="text-xl md:text-2xl font-bold text-primary" style="font-weight: 700;">书香阁</span>
            </router-link>
          </div>

          <!-- 主导航 - 桌面版 -->
          <nav class="hidden md:flex items-center space-x-8">
            <router-link to="/home" class="font-medium text-gray-600 hover:text-primary transition-colors py-1">首页</router-link>
            <router-link to="/category" class="font-medium text-gray-600 hover:text-primary transition-colors py-1">分类</router-link>
            <router-link to="/bestseller" class="font-medium text-gray-600 hover:text-primary transition-colors py-1">畅销榜</router-link>
            <router-link to="/news" class="font-medium text-gray-600 hover:text-primary transition-colors py-1">资讯</router-link>
          </nav>

          <!-- 搜索框 -->
          <div class="hidden md:flex items-center flex-1 max-w-md mx-8">
            <div class="flex w-full">
              <input
                v-model="searchKeyword"
                type="text"
                placeholder="搜索图书、作者、出版社..."
                class="flex-1 pl-4 pr-4 py-2 border border-gray-200 rounded-full focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/20 transition-all duration-300"
                @keyup.enter="handleSearch"
              >
              <button
                @click="handleSearch"
                class="search-button ml-2 px-4 py-2 text-white rounded-full transition-colors flex items-center justify-center"
              >
                <i class="fas fa-search"></i>
              </button>
            </div>
          </div>

          <!-- 右侧功能区 -->
          <div class="flex items-center space-x-4">
            <!-- 通知按钮 -->
            <button class="relative p-2 text-gray-600 hover:text-primary transition-colors">
              <i class="fas fa-bell text-lg"></i>
              <span class="absolute top-1 right-1 w-2 h-2 bg-red-500 rounded-full"></span>
            </button>

            <!-- 购物车 -->
            <button
              @click="goToCart"
              class="relative p-2 text-gray-600 hover:text-primary transition-colors"
            >
              <i class="fas fa-shopping-cart text-lg"></i>
              <span class="absolute -top-1 -right-1 bg-primary text-white text-xs rounded-full w-5 h-5 flex items-center justify-center cart-badge">{{ cartCount }}</span>
            </button>

            <!-- 用户下拉菜单 -->
            <el-dropdown @command="handleCommand">
              <span class="el-dropdown-link cursor-pointer flex items-center">
                <el-avatar :size="32" :src="getImageUrl(userStore.userInfo?.avatar)">
                  <i class="fas fa-user"></i>
                </el-avatar>
                <span class="hidden md:block ml-2 text-gray-600">{{ userStore.userInfo?.username }}</span>
                <i class="fas fa-chevron-down ml-1 text-gray-400"></i>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="profile">个人资料</el-dropdown-item>
                  <el-dropdown-item command="orders">我的订单</el-dropdown-item>
                  <el-dropdown-item command="settings">设置</el-dropdown-item>
                  <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

            <!-- 移动端菜单按钮 -->
            <button
              @click="toggleMobileMenu"
              class="md:hidden p-2 text-gray-600 hover:text-primary transition-colors"
            >
              <i class="fas fa-bars text-xl"></i>
            </button>
          </div>
        </div>
      </div>

      <!-- 移动端导航菜单 -->
      <div v-show="showMobileMenu" class="md:hidden bg-white border-t border-gray-100 shadow-lg">
        <div class="container mx-auto px-4 py-3 space-y-3">
          <!-- 导航链接 -->
          <router-link to="/home" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors">首页</router-link>
          <router-link to="/category" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors">分类</router-link>
          <router-link to="/bestseller" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors">畅销榜</router-link>
          <router-link to="/news" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors">资讯</router-link>

          <!-- 分割线 -->
          <div class="border-t border-gray-200 my-3"></div>

          <!-- 用户菜单 -->
          <div class="space-y-2">
            <div class="flex items-center py-2 px-3">
              <el-avatar :size="24" :src="getImageUrl(userStore.userInfo?.avatar)" class="mr-2">
                <i class="fas fa-user"></i>
              </el-avatar>
              <span class="text-gray-700 font-medium">{{ userStore.userInfo?.username || '用户' }}</span>
            </div>
            <router-link to="/profile" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors text-gray-600">
              <i class="fas fa-user-circle mr-2"></i>个人资料
            </router-link>
            <router-link to="/orders" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors text-gray-600">
              <i class="fas fa-shopping-bag mr-2"></i>我的订单
            </router-link>
            <router-link to="/settings" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors text-gray-600">
              <i class="fas fa-cog mr-2"></i>设置
            </router-link>
            <button @click="handleLogout" class="w-full text-left py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors text-red-600">
              <i class="fas fa-sign-out-alt mr-2"></i>退出登录
            </button>
          </div>
        </div>
      </div>
    </header>

    <!-- 主要内容 -->
    <main class="container mx-auto px-4 py-8">
      <!-- 加载状态 -->
      <div v-if="loading" class="flex justify-center items-center py-20">
        <div class="text-center">
          <i class="fas fa-spinner fa-spin text-4xl text-primary mb-4"></i>
          <p class="text-gray-600">正在加载图书详情...</p>
        </div>
      </div>

      <!-- 图书详情内容 -->
      <div v-else-if="bookData">
        <!-- 上区域：左侧缩略图、中间书籍封面、右侧书籍详情 -->
        <div class="flex flex-col lg:flex-row gap-6 lg:items-start">
        <!-- 左侧缩略图区域 -->
        <div class="lg:w-1/5 hidden lg:block">
          <div class="space-y-3">
            <div
              v-for="(thumbnail, index) in book.thumbnails"
              :key="index"
              @click="selectThumbnail(index)"
              :class="[
                'book-thumbnail cursor-pointer border-2 rounded-lg overflow-hidden transition-all duration-300',
                selectedThumbnail === index ? 'border-primary shadow-md' : 'border-transparent hover:border-gray-300'
              ]"
            >
              <img :src="thumbnail" :alt="`${book.title} 图片 ${index + 1}`" class="w-full h-24 object-cover">
            </div>
          </div>
        </div>

        <!-- 中间书籍封面 -->
        <div class="lg:w-2/5 flex justify-center">
          <div class="book-cover-wrapper relative">
            <img
              :src="book.thumbnails[selectedThumbnail]"
              :alt="book.title"
              class="w-full max-w-sm h-auto object-cover rounded-lg shadow-lg cursor-pointer transition-transform duration-300 hover:scale-105"
              @click="viewLargeImage"
            >
          </div>
        </div>

        <!-- 右侧书籍详情 -->
        <div class="lg:w-2/5 space-y-6">
          <div>
            <h1 class="text-3xl font-bold text-gray-800 mb-2">{{ book.title }}</h1>
            <p class="text-gray-600 mb-4">作者：{{ book.author }}</p>
            
            <!-- 评分 -->
            <div class="flex items-center mb-4">
              <div class="flex text-yellow-400 mr-2">
                <i v-for="n in 5" :key="n" :class="n <= book.rating ? 'fas fa-star' : 'far fa-star'"></i>
              </div>
              <span class="text-gray-600">{{ book.rating }}/5 ({{ book.reviewCount }}条评论)</span>
            </div>

            <!-- 价格 -->
            <div class="mb-6">
              <span class="text-3xl font-bold text-primary">¥{{ book.price }}</span>
              <span v-if="book.originalPrice" class="text-lg text-gray-400 line-through ml-2">¥{{ book.originalPrice }}</span>
            </div>

            <!-- 书籍信息 -->
            <div class="space-y-2 text-sm text-gray-600 mb-6">
              <div><span class="font-medium">出版社：</span>{{ book.publisher }}</div>
              <div><span class="font-medium">ISBN：</span>{{ book.isbn }}</div>
              <div><span class="font-medium">页数：</span>{{ book.pages }}页</div>
              <div><span class="font-medium">出版时间：</span>{{ book.publishDate }}</div>
              <div><span class="font-medium">装帧：</span>{{ book.binding }}</div>
            </div>

            <!-- 库存状态 -->
            <div class="mb-6">
              <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-green-100 text-green-800">
                <i class="fas fa-check-circle mr-1"></i>
                现货 {{ book.stock }}本
              </span>
            </div>

            <!-- 数量选择和购买按钮 -->
            <div class="space-y-4">
              <div class="flex items-center space-x-4">
                <span class="text-gray-700">数量：</span>
                <div class="flex items-center border border-gray-300 rounded">
                  <button @click="decreaseQuantity" class="px-3 py-1 hover:bg-gray-100">-</button>
                  <span class="px-4 py-1 border-x border-gray-300">{{ quantity }}</span>
                  <button @click="increaseQuantity" class="px-3 py-1 hover:bg-gray-100">+</button>
                </div>
              </div>

              <div class="flex space-x-4">
                <button
                  @click="addToCart"
                  class="flex-1 bg-primary text-white py-3 px-6 rounded-lg font-medium hover:bg-primary/80 transition-colors"
                >
                  <i class="fas fa-shopping-cart mr-2"></i>
                  加入购物车
                </button>
                <button
                  @click="buyNow"
                  class="flex-1 bg-orange-500 text-white py-3 px-6 rounded-lg font-medium hover:bg-orange-600 transition-colors"
                >
                  <i class="fas fa-bolt mr-2"></i>
                  立即购买
                </button>
                <button
                  @click="toggleFavorite"
                  :class="[
                    'w-12 h-12 rounded-lg border-2 flex items-center justify-center transition-all duration-300',
                    isFavorite
                      ? 'bg-red-50 border-red-300 text-red-500 hover:bg-red-100'
                      : 'bg-gray-50 border-gray-300 text-gray-400 hover:bg-gray-100 hover:border-gray-400'
                  ]"
                >
                  <i :class="isFavorite ? 'fas fa-heart' : 'far fa-heart'" class="text-xl"></i>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 下区域：书籍详情标签页 -->
      <div class="mt-12">
        <div class="bg-white rounded-xl shadow-sm overflow-hidden">
          <div class="border-b border-gray-200 flex">
            <button
              v-for="tab in tabs"
              :key="tab.key"
              @click="activeTab = tab.key"
              :class="[
                'py-4 px-6 font-medium transition-colors',
                activeTab === tab.key
                  ? 'text-primary border-b-2 border-primary'
                  : 'text-gray-500 hover:text-gray-700'
              ]"
            >
              {{ tab.label }}
            </button>
          </div>

          <div class="p-6">
            <!-- 内容简介 -->
            <div v-if="activeTab === 'description'" class="space-y-4">
              <p v-for="paragraph in book.description" :key="paragraph" class="text-gray-700 leading-relaxed">
                {{ paragraph }}
              </p>
            </div>

            <!-- 作者简介 -->
            <div v-if="activeTab === 'author'" class="space-y-4">
              <p v-for="paragraph in book.authorBio" :key="paragraph" class="text-gray-700 leading-relaxed">
                {{ paragraph }}
              </p>
            </div>

            <!-- 读者评论 -->
            <div v-if="activeTab === 'reviews'" class="space-y-6 reviews-section">
              <!-- 写评论区域 -->
              <div v-if="userStore.isLoggedIn" class="bg-gray-50 rounded-lg p-4 mb-6">
                <h4 class="font-medium text-gray-800 mb-3">写评论</h4>
                <div class="space-y-4">
                  <!-- 评分选择 -->
                  <div class="flex items-center space-x-2">
                    <span class="text-sm text-gray-600">评分：</span>
                    <div class="flex space-x-1">
                      <button
                        v-for="star in 5"
                        :key="star"
                        @click="newReview.rating = star"
                        :class="[
                          'text-2xl transition-colors',
                          star <= newReview.rating ? 'text-yellow-400' : 'text-gray-300 hover:text-yellow-300'
                        ]"
                      >
                        <i class="fas fa-star"></i>
                      </button>
                    </div>
                    <span class="text-sm text-gray-500 ml-2">{{ newReview.rating }}分</span>
                  </div>

                  <!-- 评论内容 -->
                  <div>
                    <textarea
                      v-model="newReview.content"
                      placeholder="请写下您对这本书的评价..."
                      class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/20 resize-none"
                      rows="4"
                      maxlength="500"
                    ></textarea>
                    <div class="flex justify-between items-center mt-2">
                      <span class="text-xs text-gray-500">{{ newReview.content.length }}/500</span>
                      <button
                        @click="submitReview"
                        :disabled="!newReview.content.trim() || submittingReview"
                        class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/80 disabled:bg-gray-300 disabled:cursor-not-allowed transition-colors"
                      >
                        {{ submittingReview ? '提交中...' : '发表评论' }}
                      </button>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 未登录提示 -->
              <div v-else class="bg-gray-50 rounded-lg p-4 mb-6 text-center">
                <p class="text-gray-600 mb-3">登录后可以发表评论</p>
                <button
                  @click="router.push('/login')"
                  class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/80 transition-colors"
                >
                  立即登录
                </button>
              </div>

              <!-- 评论列表 -->
              <div class="space-y-6">
                <!-- 评论统计和排序 -->
                <div class="bg-gray-50 rounded-lg p-4">
                  <div class="flex items-center justify-between">
                    <div class="flex items-center space-x-4">
                      <h4 class="font-semibold text-gray-800 text-lg">
                        <i class="fas fa-comments text-primary mr-2"></i>
                        全部评论
                      </h4>
                      <span class="bg-primary text-white px-3 py-1 rounded-full text-sm font-medium">
                        {{ reviewsData.total || 0 }}条
                      </span>
                      <div v-if="reviewsData.total > 0" class="text-sm text-gray-600">
                        当前第{{ reviewsPagination.current }}页，共{{ Math.ceil(reviewsData.total / reviewsPagination.size) }}页
                      </div>
                    </div>
                    <div class="flex items-center space-x-3">
                      <span class="text-sm text-gray-600">排序方式：</span>
                      <select
                        v-model="reviewSort"
                        @change="handleSortChange"
                        class="text-sm border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/20 bg-white"
                      >
                        <option value="time">最新发布</option>
                        <option value="rating">评分高低</option>
                        <option value="likes">点赞最多</option>
                      </select>
                    </div>
                  </div>
                </div>

                <!-- 评论加载状态 -->
                <div v-if="reviewsLoading" class="text-center py-8">
                  <i class="fas fa-spinner fa-spin text-2xl text-gray-400 mb-2"></i>
                  <p class="text-gray-500">加载评论中...</p>
                </div>

                <!-- 评论列表 -->
                <div v-else-if="reviewsData.records && reviewsData.records.length > 0" class="space-y-6">
                  <div
                    v-for="(review, index) in reviewsData.records"
                    :key="review.id"
                    class="review-card bg-white rounded-lg border border-gray-100 p-4 hover:shadow-md transition-shadow duration-200"
                  >
                    <div class="flex items-start justify-between mb-3">
                      <div class="flex items-center">
                        <!-- 用户头像 -->
                        <el-avatar :size="40" :src="getImageUrl(review.userAvatar)" class="mr-3">
                          <i class="fas fa-user"></i>
                        </el-avatar>
                        <div>
                          <div class="flex items-center">
                            <span class="font-medium text-gray-800 mr-2">{{ review.userName || '匿名用户' }}</span>
                            <!-- 评分星星 -->
                            <div class="star-rating flex text-yellow-400 mr-2">
                              <i v-for="n in 5" :key="n" :class="n <= review.rating ? 'fas fa-star text-sm' : 'far fa-star text-sm'"></i>
                            </div>
                            <span class="text-yellow-600 text-sm font-medium">{{ review.rating }}.0</span>
                          </div>
                          <span class="text-gray-500 text-sm">{{ formatDate(review.createdAt) }}</span>
                        </div>
                      </div>
                      <!-- 楼层号 -->
                      <span class="text-gray-400 text-sm">#{{ (reviewsPagination.current - 1) * reviewsPagination.size + index + 1 }}</span>
                    </div>

                    <!-- 评论内容 -->
                    <div class="ml-13">
                      <p class="text-gray-700 leading-relaxed text-base">{{ review.content }}</p>

                      <!-- 点赞按钮 -->
                      <div class="flex items-center mt-3">
                        <button
                          @click="toggleLike(review)"
                          :class="[
                            'action-button flex items-center transition-colors text-sm',
                            review.isLiked ? 'text-red-500' : 'text-gray-500 hover:text-red-500'
                          ]"
                        >
                          <i :class="review.isLiked ? 'fas fa-heart mr-1' : 'far fa-heart mr-1'"></i>
                          <span>{{ review.likes || 0 }}</span>
                        </button>
                      </div>
                    </div>
                  </div>
                </div>

                <!-- 无评论提示 -->
                <div v-else class="text-center py-8">
                  <i class="fas fa-comments text-4xl text-gray-300 mb-3"></i>
                  <p class="text-gray-500">暂无评论，快来发表第一条评论吧！</p>
                </div>

                <!-- 分页 -->
                <div v-if="reviewsData.total > 0" class="flex justify-center mt-8">
                  <el-pagination
                    v-model:current-page="reviewsPagination.current"
                    v-model:page-size="reviewsPagination.size"
                    :total="reviewsData.total"
                    :page-sizes="[5, 10, 15, 20]"
                    layout="total, sizes, prev, pager, next, jumper"
                    :pager-count="7"
                    :small="false"
                    background
                    @current-change="handlePageChange"
                    @size-change="handleSizeChange"
                    class="pagination-custom"
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 相关推荐区域 -->
      <section class="mt-16">
        <div class="flex items-center justify-between mb-6">
          <h2 class="text-2xl font-bold text-gray-800">相关推荐</h2>
        </div>

        <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-4">
          <div
            v-for="relatedBook in relatedBooks"
            :key="relatedBook.id"
            @click="goToBookDetail(relatedBook.id)"
            class="bg-white rounded-xl overflow-hidden shadow-sm hover:shadow-lg transition-all duration-300 transform hover:-translate-y-1 border border-gray-100 cursor-pointer"
          >
            <div class="relative">
              <img
                :src="relatedBook.cover"
                :alt="relatedBook.title"
                class="w-full h-48 object-cover"
              >
              <div v-if="relatedBook.tag" :class="`absolute top-3 left-3 text-white text-xs font-bold px-2 py-1 rounded ${relatedBook.tagColor}`">
                {{ relatedBook.tag }}
              </div>
            </div>
            <div class="p-3">
              <h3 class="font-bold text-sm mb-1 line-clamp-1 text-gray-800">{{ relatedBook.title }}</h3>
              <p class="text-gray-500 text-xs mb-1 line-clamp-1">{{ relatedBook.author }}</p>
              <div class="flex items-center justify-between">
                <span class="text-primary font-bold text-sm">¥{{ relatedBook.price }}</span>
                <button
                  @click.stop="addToCartFromRecommended(relatedBook)"
                  class="w-8 h-8 rounded-full bg-primary/10 text-primary flex items-center justify-center hover:bg-primary hover:text-white transition-colors"
                >
                  <i class="fas fa-shopping-cart text-sm"></i>
                </button>
              </div>
            </div>
          </div>
        </div>
      </section>
      </div>

      <!-- 图书不存在或加载失败 -->
      <div v-else class="flex justify-center items-center py-20">
        <div class="text-center">
          <i class="fas fa-exclamation-triangle text-4xl text-gray-400 mb-4"></i>
          <p class="text-gray-600 mb-4">图书信息加载失败</p>
          <button @click="router.push('/home')" class="px-6 py-2 bg-primary text-white rounded-lg hover:bg-primary/80 transition-colors">
            返回首页
          </button>
        </div>
      </div>
    </main>

    <!-- 回到顶部按钮 -->
    <BackToTop />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useCartStore } from '@/stores/cart'
import { ElMessage, ElDropdown, ElDropdownMenu, ElDropdownItem, ElAvatar, ElPagination } from 'element-plus'
import ggbondImg from '@/assets/images/ggbond.png'
import BackToTop from '@/components/BackToTop.vue'
import { bookAPI } from '@/api/book.js'
import { userAPI } from '@/api/user.js'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const cartStore = useCartStore()

// 响应式数据
const searchKeyword = ref('')
const showMobileMenu = ref(false)
const selectedThumbnail = ref(0)
const quantity = ref(1)
const activeTab = ref('description')
const isFavorite = ref(false)
const loading = ref(false)
const bookData = ref(null)

// 评论相关数据
const reviewsData = ref({ records: [], total: 0, size: 5 })
const reviewsLoading = ref(false)
const reviewsPagination = reactive({ current: 1, size: 5 })
const reviewSort = ref('time')
const submittingReview = ref(false)
const newReview = reactive({
  rating: 5,
  content: ''
})

// 购物车数量，使用cartStore
const cartCount = computed(() => cartStore.cartCount)

// 标签页配置
const tabs = [
  { key: 'description', label: '内容简介' },
  { key: 'author', label: '作者简介' },
  { key: 'reviews', label: '读者评论' }
]

// 检查收藏状态
const checkFavoriteStatus = async (bookId) => {
  if (!userStore.isLoggedIn) {
    isFavorite.value = false
    return
  }

  try {
    const response = await userAPI.checkFavoriteStatus(bookId)
    if (response && response.code === 200) {
      isFavorite.value = response.data.isFavorite
    }
  } catch (error) {
    console.error('检查收藏状态失败:', error)
    isFavorite.value = false
  }
}

// 加载图书详情数据
const loadBookDetail = async (bookId) => {
  loading.value = true
  try {
    const response = await bookAPI.getBookDetail(bookId)
    if (response && response.code === 200) {
      const book = response.data

      // 处理图书数据，确保格式兼容
      bookData.value = {
        ...book,
        price: book.price ? book.price.toString() : '0.00',
        originalPrice: book.originalPrice ? book.originalPrice.toString() : null,
        publishDate: book.publishDate || '未知',
        pages: book.pages || 0,
        binding: book.binding || '平装',
        rating: book.rating || 4.5,
        reviewCount: book.reviewCount || 0,
        stock: book.stock || 0,
        // 处理封面图片，如果没有封面则使用默认图片
        thumbnails: book.cover ? [getImageUrl(book.cover), getImageUrl(book.cover), getImageUrl(book.cover), getImageUrl(book.cover)] : [ggbondImg, ggbondImg, ggbondImg, ggbondImg],
        // 处理描述信息，如果是字符串则转换为数组
        description: book.description ? (Array.isArray(book.description) ? book.description : [book.description]) : ['暂无内容简介'],
        authorBio: book.authorBio ? (Array.isArray(book.authorBio) ? book.authorBio : [book.authorBio]) : ['暂无作者简介']
      }

      // 检查收藏状态
      await checkFavoriteStatus(bookId)
    } else {
      ElMessage.error(response?.message || '获取图书详情失败')
      bookData.value = null
    }
  } catch (error) {
    console.error('加载图书详情失败:', error)
    ElMessage.error('加载图书详情失败，请稍后重试')
    bookData.value = null
  } finally {
    loading.value = false
  }
}

// 当前图书数据
const book = computed(() => {
  return bookData.value || {
    title: '加载中...',
    author: '加载中...',
    publisher: '加载中...',
    price: '0.00',
    thumbnails: [ggbondImg],
    description: ['加载中...'],
    authorBio: ['加载中...'],
    reviews: [],
    rating: 0,
    reviewCount: 0,
    stock: 0,
    pages: 0,
    publishDate: '加载中...',
    binding: '加载中...',
    isbn: '加载中...'
  }
})

// 相关推荐图书数据
const relatedBooks = reactive([])

// 加载相关推荐图书
const loadRelatedBooks = async () => {
  try {
    const response = await bookAPI.getRecommendedBooks(6)
    if (response && response.code === 200) {
      const books = response.data.map(book => ({
        ...book,
        price: book.price ? book.price.toString() : '0.00',
        cover: getImageUrl(book.cover) || ggbondImg,
        tag: book.tags && book.tags.length > 0 ? book.tags[0].name : '推荐',
        tagColor: book.tags && book.tags.length > 0 ? book.tags[0].tagColor : 'bg-blue-500'
      }))
      relatedBooks.splice(0, relatedBooks.length, ...books)
    }
  } catch (error) {
    console.error('加载相关推荐失败:', error)
    // 如果加载失败，使用默认数据
    const defaultBooks = [
      {
        id: 2,
        title: '人间词话',
        author: '王国维',
        price: '36.50',
        cover: ggbondImg,
        tag: '经典',
        tagColor: 'bg-green-500'
      },
      {
        id: 3,
        title: 'JavaScript高级程序设计',
        author: 'Nicholas C. Zakas',
        price: '108.00',
        cover: ggbondImg,
        tag: '技术',
        tagColor: 'bg-blue-500'
      }
    ]
    relatedBooks.splice(0, relatedBooks.length, ...defaultBooks)
  }
}

// 方法
const toggleMobileMenu = () => {
  showMobileMenu.value = !showMobileMenu.value
}

const handleSearch = () => {
  if (searchKeyword.value.trim()) {
    ElMessage.info(`搜索功能开发中，搜索关键词：${searchKeyword.value}`)
  }
}

const selectThumbnail = (index) => {
  selectedThumbnail.value = index
}

const viewLargeImage = () => {
  ElMessage.info('查看大图功能开发中...')
}

const decreaseQuantity = () => {
  if (quantity.value > 1) {
    quantity.value--
  }
}

const increaseQuantity = () => {
  if (quantity.value < book.value.stock) {
    quantity.value++
  }
}

// 添加到购物车方法修改
const addToCart = async () => {
  try {
    await cartStore.addToCart(book.value, quantity.value)
    // 消息提示已在store中处理，这里不需要重复提示
  } catch (error) {
    console.error('添加到购物车失败:', error)
    // 错误提示已在cart store中处理，这里不需要重复提示
  }
}

const buyNow = () => {
  // 设置立即购买商品
  cartStore.setBuyNowItem(book.value, quantity.value)

  // 跳转到结算页面
  router.push('/checkout')

  ElMessage.success(`已选择立即购买《${book.value.title}》，数量：${quantity.value}`)
}

const goToBookDetail = (bookId) => {
  router.push(`/book/${bookId}`)
}

const toggleFavorite = async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  try {
    const response = await userAPI.toggleFavorite(bookData.value.id)
    if (response && response.code === 200) {
      isFavorite.value = response.data.isFavorite
      ElMessage.success(response.data.message)
    } else {
      ElMessage.error(response?.message || '操作失败')
    }
  } catch (error) {
    console.error('切换收藏状态失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}

// 从推荐商品添加到购物车
const addToCartFromRecommended = async (relatedBook) => {
  try {
    await cartStore.addToCart(relatedBook)
    // 消息提示已在store中处理，这里不需要重复提示
  } catch (error) {
    console.error('添加到购物车失败:', error)
  }
}

const goToCart = () => {
  router.push('/cart')
}

// 评论相关方法
const loadReviews = async () => {
  if (!bookData.value) return

  reviewsLoading.value = true
  try {
    const params = {
      current: reviewsPagination.current,
      size: reviewsPagination.size,
      sort: reviewSort.value
    }

    const response = await bookAPI.getBookReviews(bookData.value.id, params)
    if (response && response.code === 200) {
      reviewsData.value = response.data
    } else {
      reviewsData.value = { records: [], total: 0, size: 10 }
    }
  } catch (error) {
    console.error('加载评论失败:', error)
    reviewsData.value = { records: [], total: 0, size: 10 }
  } finally {
    reviewsLoading.value = false
  }
}

const submitReview = async () => {
  if (!newReview.content.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }

  if (!bookData.value) {
    ElMessage.error('图书信息不存在')
    return
  }

  submittingReview.value = true
  try {
    const reviewData = {
      content: newReview.content.trim(),
      rating: newReview.rating
    }

    const response = await bookAPI.createBookReview(bookData.value.id, reviewData)
    if (response && response.code === 200) {
      ElMessage.success('评论发表成功')
      // 重置评论表单
      newReview.content = ''
      newReview.rating = 5
      // 重新加载评论列表
      reviewsPagination.current = 1
      await loadReviews()
      // 重新加载书籍详情以更新评论数
      await loadBookDetail(bookData.value.id)
    } else {
      ElMessage.error(response?.message || '评论发表失败')
    }
  } catch (error) {
    console.error('提交评论失败:', error)
    ElMessage.error('评论发表失败，请稍后重试')
  } finally {
    submittingReview.value = false
  }
}

const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 点赞功能
const toggleLike = async (review) => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    return
  }

  try {
    const response = await bookAPI.toggleReviewLike(review.id)
    if (response?.code === 200) {
      review.isLiked = !review.isLiked
      review.likes = review.isLiked ? (review.likes || 0) + 1 : Math.max((review.likes || 0) - 1, 0)
    } else {
      ElMessage.error(response?.message || '操作失败')
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 分页处理函数
const handlePageChange = (page) => {
  reviewsPagination.current = page
  loadReviews()
  // 滚动到评论区域
  scrollToReviews()
}

const handleSizeChange = (size) => {
  reviewsPagination.size = size
  reviewsPagination.current = 1 // 重置到第一页
  loadReviews()
  // 滚动到评论区域
  scrollToReviews()
}

const handleSortChange = () => {
  reviewsPagination.current = 1 // 重置到第一页
  loadReviews()
  // 滚动到评论区域
  scrollToReviews()
}

const scrollToReviews = () => {
  // 滚动到评论区域
  const reviewsSection = document.querySelector('.reviews-section')
  if (reviewsSection) {
    reviewsSection.scrollIntoView({
      behavior: 'smooth',
      block: 'start'
    })
  }
}

// 处理下拉菜单命令
const handleCommand = (command) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'orders':
      router.push('/orders')
      break
    case 'settings':
      router.push('/settings')
      break
    case 'logout':
      handleLogout()
      break
  }
}

// 处理登出
const handleLogout = () => {
  userStore.logout()
  ElMessage.success('已退出登录')
  router.push('/login')
}

// 获取图片URL
const getImageUrl = (url) => {
  if (!url) return ''

  // 如果是完整的URL，直接返回
  if (url.startsWith('http')) {
    return url
  }

  // 如果是上传的文件路径
  if (url.startsWith('/uploads/')) {
    return `http://localhost:8081/api${url}`
  }

  // 如果是静态资源路径
  if (url.startsWith('/assets/')) {
    return `http://localhost:8081/api${url}`
  }

  // 其他情况，添加API前缀
  return `/api${url}`
}

// 页面加载时的处理
onMounted(async () => {
  const bookId = parseInt(route.params.id)

  // 验证bookId是否有效
  if (!bookId || isNaN(bookId)) {
    ElMessage.error('无效的图书ID')
    router.push('/home')
    return
  }

  // 加载图书详情
  await loadBookDetail(bookId)

  // 加载相关推荐
  await loadRelatedBooks()

  // 加载评论列表
  await loadReviews()

  // 设置页面标题
  if (bookData.value) {
    document.title = `${bookData.value.title} - 书香阁`
  }

  // 如果加载失败，跳转回首页
  if (!bookData.value) {
    setTimeout(() => {
      router.push('/home')
    }, 2000)
  }
})
</script>

<style scoped>
/* 分页组件自定义样式 */
.pagination-custom {
  --el-pagination-font-size: 14px;
  --el-pagination-bg-color: #ffffff;
  --el-pagination-text-color: #606266;
  --el-pagination-border-radius: 6px;
  --el-pagination-button-color: #606266;
  --el-pagination-hover-color: #409eff;
  --el-pagination-button-bg-color: #f5f7fa;
  --el-pagination-button-disabled-color: #c0c4cc;
  --el-pagination-button-disabled-bg-color: #fff;
  --el-pagination-hover-bg-color: #409eff;
}

/* 评论区域样式优化 */
.reviews-section {
  scroll-margin-top: 100px; /* 为固定头部留出空间 */
}

/* 评论卡片动画 */
.review-card {
  transition: all 0.3s ease;
}

.review-card:hover {
  transform: translateY(-2px);
}

/* 星星评分样式 */
.star-rating {
  display: inline-flex;
  align-items: center;
}

.star-rating i {
  transition: color 0.2s ease;
}

/* 按钮悬停效果 */
.action-button {
  transition: all 0.2s ease;
}

.action-button:hover {
  transform: scale(1.05);
}

/* 用户头像渐变色变化 */
.user-avatar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.user-avatar:nth-child(2n) {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.user-avatar:nth-child(3n) {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.user-avatar:nth-child(4n) {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.user-avatar:nth-child(5n) {
  background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
}

/* 自定义样式 */
.book-thumbnail {
  transition: all 0.3s ease;
}

.book-thumbnail:hover {
  transform: translateY(-2px);
}

.book-cover-wrapper img {
  max-height: 500px;
}

/* 响应式调整 */
@media (max-width: 1024px) {
  .book-cover-wrapper img {
    max-height: 400px;
  }
}

@media (max-width: 768px) {
  .book-cover-wrapper img {
    max-height: 300px;
  }
}

/* 确保与Tailwind配置的primary颜色一致 */

/* 搜索按钮样式 */
.search-button {
  background-color: #FF6B8B !important;
}

.search-button:hover {
  background-color: rgba(255, 107, 139, 0.8) !important;
}

.cart-badge {
  z-index: 10;
  transform: translate(25%, -25%);
  min-width: 18px;
  height: 18px;
}
</style>
